package com.zlm.common.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zlm.common.dto.WechatResultDto;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Map;

/**
 * 微信通用工具类
 * @Author: duyufu
 * @Date: 2019/4/10 10:27
 */
public class WeChatUtils {

    public static String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd43950c73bac3850&secret" +
            "=SECRET&code=%s&grant_type=authorization_code";
    public static String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
    public static String checkAccessToken = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s";
    /**
     * 获取微信返回结果集
     * @param code
     * @return
     */
    public static WechatResultDto getWechatResult(String code) {
        String wechatUrl = String.format(getAccessTokenUrl,code);
        URI uri = URI.create(wechatUrl);
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(uri);
        HttpResponse response;
        try {
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    sb.append(temp);
                }
                WechatResultDto wechatResult = (WechatResultDto)FastJsonUtils.convertJsonToObject(sb.toString(),
                        WechatResultDto.class);
                return wechatResult;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户信息
     * @param accessToken
     * @param openid
     */
    public static WechatResultDto getUserInfo(String accessToken,String openid) {
        if (isAccessTokenIsInvalid(accessToken,openid)) {
            String wechatUrl = String.format(getUserInfoUrl,accessToken,openid);
            URI uri = URI.create(wechatUrl);
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(uri);
            try {
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                        sb.append(temp);
                    }
                    WechatResultDto wechatResult = (WechatResultDto)FastJsonUtils.convertJsonToObject(sb.toString(),
                            WechatResultDto.class);
                    return wechatResult;
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 检查access_token是否合法
     * @param accessToken
     * @param openid
     * @return
     */
    private static boolean isAccessTokenIsInvalid(String accessToken,String openid) {
        String wechatUrl = String.format(checkAccessToken,accessToken,openid);
        URI uri = URI.create(wechatUrl);
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(uri);
        HttpResponse response;
        try {
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuilder sb = new StringBuilder();

                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    sb.append(temp);
                }
                WechatResultDto wechatResult = (WechatResultDto)FastJsonUtils.convertJsonToObject(sb.toString(),
                        WechatResultDto.class);
                Integer errorCode = wechatResult.getErrcode();
                if (errorCode == 0) {
                    return true;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
}
